{include file="public/header" /}
<style>
    .guigeuploadimg{
        width: 50px;
        height: 50px;
    }
</style>
<body class="gray-bg">
<div class="wrapper wrapper-content">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5>编辑商品</h5>
                </div>
                <div class="ibox-content layui-form">
                    <div class="layui-row layui-col-space10 layui-form-item ">
                        <input type="hidden" name="good_id" value="{$data.good_id}" />
                        <div class="layui-form-item layui-col-md-offset1 layui-col-md8">
                            <label class="layui-form-label">商品名称：</label>
                            <div class="layui-input-block">
                                <input type="text" name="good_name" lay-verify="required" placeholder="商品名称" class="layui-input" value="{$data.good_name}">
                            </div>
                        </div>
                        <div class="layui-form-item layui-col-md-offset1 layui-col-md8">
                            <label class="layui-form-label">缩略图：</label>
                            <input type="hidden" name="good_thumb" id="lay-img" lay-verify="image" value="{$data.good_thumb}">
                            <div class="layui-input-block">
                                <div id="lay-upload">上传图片</div>
                                <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                                    预览图：
                                    <div class="layui-upload-list" id="lay-list">
                                        <img class="layui-append-img" src="{$data.good_thumb}" onerror="this.src='/static/admin/images/no_img.jpg'">
                                    </div>
                                </blockquote>
                            </div>
                        </div>

                        <div class="layui-form-item layui-col-md-offset1 layui-col-md10">
                            <label class="layui-form-label">图片详情轮播</label>
                            <div class="layui-input-block">
                                <input type="hidden" name="del" id="del2" value="">
                                <input type="hidden" id="hid2" value="{$data.good_image}">
                                <input type="hidden" name="good_image" id="photo2" value="{$data.good_image}">
                                <div id="uploader2" class="container-s">
                                    <div class="queueList">
                                        <div class="placeholder">
                                            <div id="filePicker2"></div>
                                            <p>或将照片拖到这里</p>
                                        </div>
                                    </div>
                                    <div class="statusBar" style="display:none;">
                                        <div class="layui-progress layui-progress-big active-s" lay-showpercent="true">
                                            <div class="layui-progress-bar layui-bg-blue" lay-percent="0%">
                                            </div>
                                            <span></span>
                                        </div>
                                        <div class="info"></div>
                                        <div class="btns">
                                            <div id="goPicker2" class="filePicker2"></div>
                                            <div class="uploadBtn">开始上传</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item layui-col-md-offset1 layui-col-md8">
                            <label class="layui-form-label">总库存：</label>
                            <div class="layui-input-block">
                                <input type="number" min="0" name="good_stock" value="{$data.good_stock}" lay-verify="required" placeholder="总库存" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item layui-col-md-offset1 layui-col-md8">
                            <label class="layui-form-label">价格：</label>
                            <div class="layui-input-block">
                                <input type="text" name="good_price" value="{$data.good_price}" lay-verify="required" placeholder="商品价格" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item layui-col-md-offset1 layui-col-md10">
                            <label class="layui-form-label">商品详情：</label>
                            <div class="layui-input-block" id="LAY_editor" lay-verify="editor">
                                <p>{$data.good_content}</p>
                            </div>
                        </div>
                        <div class="layui-form-item layui-col-md-offset1 layui-col-md8" id="user_id">
                            <label class="layui-form-label">学校(非必填)：</label>
                            <div class="layui-input-block">
                                <select name="good_school" xm-select="select1" xm-select-search="" xm-select-radio="" xm-select-search-type="dl">
                                    <option value="">没有关联学校</option>
                                    {volist name='school' id='s'}
                                    <option value="{$s.school_id}" {if $s.school_id == $data.good_school}selected{/if} >{$s.school_id}</option>
                                    {/volist}
                                </select>
                            </div>
                        </div>
                        <div class="layui-form-item layui-col-md-offset1 layui-col-md8">
                            <label class="layui-form-label">商品状态：</label>
                            <div class="layui-input-block">
                                <select name="good_status">
                                    <option value="1" {if $data.good_status == 1}selected{/if}>上架</option>
                                    <option value="2" {if $data.good_status == 2}selected{/if}>下架</option>
                                </select>
                            </div>
                        </div>

                        <!--规格 start -->
                        <div style="z-index: 9999999;clear: both;">
                        <div class="control-group">
                            <label class="control-label"> </label>
                            <div class="controls">
                                <button id="add_lv1" class="btn btn-primary" type="button">添加规格项</button>
                                <button id="update_table" class="btn btn-success" type="button">生成/刷新规格项目表</button>
                            </div>
                            {volist name='guige' id='g'}
                            <div class="control-group lv1">
                                <label class="control-label">规格名称</label>
                                <div class="controls">
                                    <input type="text" name="lv1" class="layui-input guige1" style="width: 150px;display: inline-table;"
                                           placeholder="规格名称" value="{$g.attr_group_name}" readonly>
                                    <button class="btn btn-primary add_lv2" type="button">添加参数</button>
                                    <button class="btn btn-danger remove_lv1" type="button">删除规格</button>
                                </div>
                                <div class="controls lv2s">
                                    {volist name='g.attr_list' id='ga'}
                                    <div style="margin-top: 5px;">
                                        <input type="text" name="lv2" placeholder="参数名称" class="layui-input guige2"
                                               style="width: 150px;display: inline-table;" value="{$ga.attr_name}" readonly>
                                        <button class="btn btn-danger remove_lv2" type="button">删除参数</button>
                                    </div>
                                    {/volist}
                                </div>
                            </div>
                            {/volist}
                        </div>
                        <div id="lv_table_con" class="control-group">
                            <label class="control-label">规格项目表</label>
                            <div class="controls">
                                <div id="lv_table">
                                </div>
                            </div>
                        </div>
                        </div>

                        <input type="hidden" name="gg_json" id="gg_json" value="" />
                        <input type="hidden" name="attr_json" id="attr_json" value="" />
                        <input type="hidden" name="havechange" id="havechange" value="1" />
                        <!--规格  end -->

                        <div class="layui-form-item layui-col-md-offset1 layui-col-md8">
                            <div class="layui-input-block">
                                <button class="layui-btn" lay-submit="" lay-filter="component-form-element">保存
                                </button>
                                <button class="layui-btn layui-btn-primary" onclick="history.go(-1)">关闭</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

{include file="public/footer" /}
<script>
    wk.uploadImg({size:5,type:'png,jpg,jpeg',url:"{:url('Upload/upload')}",domain:""});
    var n2 = wk.uploads({num:8,type:'png,jpg,gif',attr:2,status:'update'})
    function imgDel2(e,obj,hid,del){
        wk.update_del(e,obj,hid,del,n2);
    }
    var editor = wk.wang({elem:'#LAY_editor'});
    layui.use(['form','upload','layedit','laydate'], function() {
        var form = layui.form;
        form.verify({
            editor:function(value,item){
                if(editor.txt.html() == '<p><br></p>'){
                    return '请填写内容';
                }
            }
        });

        form.on('submit(component-form-element)', function (data) {
            var submit_status = submitCan();
            if(submit_status.status == false){
                alert(submit_status.msg);
                return false;
            }else{
                data.field.content = editor.txt.html();
                data.field.attr_json = $('#attr_json').val();
                data.field.gg_json = $('#gg_json').val();
                $('.layui-btn').addClass('layui-disabled').attr('disabled','disabled');
                $.ajax({
                    url:"{:url('goodEdit')}",
                    type:'post',
                    dataType:'json',
                    data:data.field,
                    success:function(res){
                        if (res.code == 200) {
                            wk.success(res.msg,"{:url('Goods/index')}")
                        } else {
                            wk.error(res.msg,'','$(".layui-btn").removeClass(\'layui-disabled\').removeAttr(\'disabled\');');
                        }
                    }
                })
            }

        });
    });
</script>

</body>
</html>
<script>
    var lv1HTML = '<div class="control-group lv1">' +
        '<label class="control-label">规格名称</label>' +
        '<div class="controls">' +
        '<input type="text" name="lv1" class="layui-input guige1" style="width: 150px;display: inline-table;" placeholder="规格名称"> ' +
        '<button class="btn btn-primary add_lv2" type="button">添加参数</button> ' +
        '<button class="btn btn-danger remove_lv1" type="button">删除规格</button>' +
        '</div>' +
        '<div class="controls lv2s"></div>' +
        '</div>';

    var lv2HTML = '<div style="margin-top: 5px;">' +
        '<input type="text" name="lv2" placeholder="参数名称" class="layui-input guige2" style="width: 150px;display: inline-table;"> ' +
        '<button class="btn btn-danger remove_lv2" type="button">删除参数</button>' +
        '</div>';

    $(document).ready(function() {
        var attrs = {$atrrs};
        $('#add_lv1').on('click', function() {
            emptygg();//------每一次的点击都重新生成表格----
            var last = $('.control-group.lv1:last');
            if (!last || last.length == 0) {
                $(this).parents('.control-group').eq(0).after(lv1HTML);
            } else {
                last.after(lv1HTML);
            }
        });

        $(document).on('click', '.remove_lv1', function() {
            emptygg();//------每一次的点击都重新生成表格----
            $(this).parents('.lv1').remove();
        });

        $(document).on('click', '.add_lv2', function() {
            emptygg();//------每一次的点击都重新生成表格----
            $(this).parents('.lv1').find('.lv2s').append(lv2HTML);
        });

        $(document).on('click', '.remove_lv2', function() {
            emptygg();//------每一次的点击都重新生成表格----
            $(this).parent().remove();
        });

        $('#update_table').on('click', function() {
            //----生成表格时候判断能不能生成 start ---
            if($('.guige1').length > 0){
                var ggstatus = true;
                var ggstr = '';
                var ggvalue = [];
                $('.guige1').each(function (i,d) {
                    var now_gg_value = d.value.trim();
                    if(now_gg_value == ''){
                        ggstatus = false;
                        ggstr = '规格项不能为空！';
                        return false;
                    }else{
                        if(ggvalue.indexOf(now_gg_value) == -1){
                            ggvalue.push(now_gg_value);
                        }
                    }
                });
                if (ggstatus == false) {
                    alert(ggstr);
                    return;
                }
                if (ggvalue.length != $('.guige1').length) {
                    alert('请删除值重复的规格项！');
                    return;
                }
            }
            //----生成表格时候判断能不能生成 end -----
            var lv1Arr = $('input[name="lv1"]');
            if (!lv1Arr || lv1Arr.length == 0) {
                $('#lv_table_con').hide();
                $('#lv_table').html('');
                return;
            }
            for (var i = 0; i < lv1Arr.length; i++) {
                var lv2Arr = $(lv1Arr[i]).parents('.lv1').find('input[name="lv2"]');
                if (!lv2Arr || lv2Arr.length == 0) {
                    alert('请先删除无参数的规格项！');
                    return;
                }
                //参数值的判断-start-
                var ggstatus = true;
                var ggstr = '';
                var ggvalue = [];
                lv2Arr.each(function (i,d) {
                    var now_gg_value = d.value.trim();
                    if(now_gg_value == ''){
                        ggstatus = false;
                        ggstr = '参数值不能为空！';
                        return false;
                    }else{
                        if(ggvalue.indexOf(now_gg_value) == -1){
                            ggvalue.push(now_gg_value);
                        }
                    }
                })
                if (ggstatus == false) {
                    alert(ggstr);
                    return;
                }
                if (ggvalue.length != lv2Arr.length) {
                    alert('请删除值重复的参数项！');
                    return;
                }
                //参数值的判断-end-
            }

            var tableHTML = '';
            tableHTML += '<table class="table table-bordered">';
            tableHTML += '    <thead>';
            tableHTML += '        <tr>';
            for (var i = 0; i < lv1Arr.length; i++) {
                tableHTML += '<th width="50">' + $(lv1Arr[i]).val() + '</th>';
            }
            tableHTML += '            <th width="20">价格</th>';
            tableHTML += '            <th width="20">库存</th>';
            tableHTML += '            <th width="20">货号</th>';
            tableHTML += '            <th width="20">重量</th>';
            tableHTML += '            <th width="20">规格图片</th>';
            tableHTML += '        </tr>';
            tableHTML += '    </thead>';
            tableHTML += '    <tbody>';

            var numsArr = new Array();
            var idxArr = new Array();
            //numsArr记录每个规格又多少个参数，并用idxarr记录规格数组下标 方便后边标记name
            for (var i = 0; i < lv1Arr.length; i++) {
                numsArr.push($(lv1Arr[i]).parents('.lv1').find('input[name="lv2"]').length);
                idxArr[i] = 0;
            }

            var len = 1;
            var rowsArr = new Array();
            for (var i = 0; i < numsArr.length; i++) {
                //len  记录参数总行数
                len = len * numsArr[i];

                var tmpnum = 1;
                for (var j = numsArr.length - 1; j > i; j--) {
                    tmpnum = tmpnum * numsArr[j];
                }
                //当前规格每个参数所占行数
                rowsArr.push(tmpnum);
            }

            for (var i = 0; i < len; i++) {
                tableHTML += '        <tr data-row="' + (i+1) + '">';

                var name = '';
                var name2 = '';
                for (var j = 0; j < lv1Arr.length; j++) {
                    var n = parseInt(i / rowsArr[j]);
                    if (j == 0) {
                    } else if (j == lv1Arr.length - 1) {
                        n = idxArr[j];
                        if (idxArr[j] + 1 >= numsArr[j]) {
                            idxArr[j] = 0;
                        } else {
                            idxArr[j]++;
                        }
                    } else {
                        var m = parseInt(i / rowsArr[j]);
                        n = m % numsArr[j];
                    }

                    var text = $(lv1Arr[j]).parents('.lv1').find('input[name="lv2"]').eq(n).val();
                    var obj2 = $(lv1Arr[j]).parents('.lv1').find('input[name="lv2"]').eq(n);
                    var attrid2 = $('.guige2').index(obj2) - 0 + 1;
                    if (j != lv1Arr.length - 1) {
                        name += text + '/';
                        name2 += attrid2 + ':';
                    } else {
                        name += text;
                        name2 += attrid2;
                    }

                    if (i % rowsArr[j] == 0) {
                        tableHTML += '<td width="50" rowspan="' + rowsArr[j] + '" data-rc="' + (i+1) + '_' + (j+1) + '">' + text + '</td>';
                    }
                }
//
                var attrsprice = '';
                var attrsstock = '';
                var attrsno = '';
                var attrsweight = '';
                var attrspic_url = '';
                var attrspic_url2 = '';
                var havechange = $('#havechange').val();
                if(havechange == 1){
                    attrspic_url = attrs[name2]['pic_url'];
                    attrspic_url2 = attrs[name2]['pic_url'];
                    if(attrs[name2]['pic_url'] == ''){
                        attrspic_url = '';
                        attrspic_url2 = '__IMG__/addpic.png';
                    }
                    attrsprice = attrs[name2]['price'];
                    attrsstock = attrs[name2]['stock'];
                    attrsno = attrs[name2]['no'];
                    attrsweight = attrs[name2]['weight'];
                }else{
                    attrspic_url = '';
                    attrspic_url2 = '__IMG__/addpic.png';
                }

                tableHTML += '<td width="20"><input lay-verify="required" class="layui-input attrinput" value="'+attrsprice+'" type="text" data-attrstr="' + name + '" data-attrid="' + name2 + '" /></td>';
                tableHTML += '<td width="20"><input lay-verify="required" class="layui-input attrinput" value="'+attrsstock+'" type="number" min="0" data-attrstr="' + name + '" data-attrid="' + name2 + '" /></td>';
                tableHTML += '<td width="20"><input lay-verify="required" class="layui-input attrinput" value="'+attrsno+'" type="text" data-attrstr="' + name + '" data-attrid="' + name2 + '" /></td>';
                tableHTML += '<td width="20"><input lay-verify="required" class="layui-input attrinput" value="'+attrsweight+'" type="text" data-attrstr="' + name + '" data-attrid="' + name2 + '" /></td>';
                tableHTML += '<input type="hidden" class="attrinput" id="guigeimgsrcinput'+i+'" value="'+attrspic_url+'" />';
                tableHTML += '<td width="20"><img class="guigeuploadimg" data-id="'+i+'" id="guigeimgsrc'+i+'" src="'+attrspic_url2+'" alt="" /></td>';
                tableHTML += '<input type="file" accept="image/*" id="guigefileimg'+i+'" data-id="'+i+'" onChange="previewimg(this)" style="display:none;" />';
                tableHTML += '</tr>';
            }
            tableHTML += '</tbody>';
            tableHTML += '</table>';

            $('#lv_table_con').show();
            $('#lv_table').html(tableHTML);
            //触发点击事件要放在里面
            $('.guigeuploadimg').click(function () {
                var i = $(this).attr('data-id');
                $('#guigefileimg'+i).click();
            });
            $(".guige1,.guige2").prop("readonly",true);
        });
        $('#update_table').trigger('click');
    });
    //触发上传事件要放在外面
    function previewimg(obj){
        var src = window.URL.createObjectURL(obj.files[0]);
//
        var reader = new FileReader();
        //获取文件
        var file = obj.files[0];
        var imageType = /^image\//;
        //是否是图片
        if(!imageType.test(file.type)) {
            alert("请选择图片！");
            return;
        }
//
        //读取完成
        var i = $(obj).attr('data-id');
            reader.onload = function(e) {
//            $('#guigeimgsrc'+i).attr('src',src);
        };
        reader.readAsDataURL(file);
//
        var formData = new FormData();
        formData.append('file', $('#guigefileimg'+i)[0].files[0]);  //添加图片信息的参数
        $.ajax({
            url: '/admin/Upload/uploadForGuige',
            type: 'POST',
            data: formData,
            async: false,//1
            cache: false,//2
            contentType: false,//3
            processData: false,//4
            success: function (returnData) {
                if(returnData.code == 200){
                    $('#guigeimgsrcinput'+i).val(returnData.msg);
                    $('#guigeimgsrc'+i).attr('src',src);
                    return true;
                }else{
                    $('#guigeimgsrcinput'+i).val('');
                    alert('上传失败，请重试')
                    return false;
                }
            },
            error: function (data) {
                alert("上传失败");
            }
        });
    }
    function emptygg() {
        $('#lv_table_con').hide();
        $('#lv_table').html('');
        $('#gg_json').val('');
        $('#attr_json').val('');
        $(".guige1,.guige2").prop("readonly",false);
//
        $('#havechange').val(2);
        return;
    }

</script>
<script>
    function submitCan() {
        var res = [];
        res['status'] = true;
        res['msg'] = 'ok';
        //-----------------------------处理填写的规格：------------------------------
        var lv1Arr = $('input[name="lv1"]');
        if (!lv1Arr || lv1Arr.length == 0) {
            res['status'] = false;
            res['msg'] = '请完善规格！';
            return res;
        }
        var level_1 = {};
        var son = 1;
        for (var i = 0; i < lv1Arr.length; i++) {
            var level_2 = {};
            //塞值
            level_1[i] = {};
            level_1[i]['attr_group_id'] = i - 0 + 1;
            level_1[i]['attr_group_name'] = lv1Arr[i].value.trim();

            var lv2Arr = $(lv1Arr[i]).parents('.lv1').find('input[name="lv2"]');
            if (!lv2Arr || lv2Arr.length == 0) {
                res['status'] = false;
                res['msg'] = '请完善规格！';
                return res;
            }
            //参数值的判断-start-
            var ggstatus = true;
            var ggstr = '';
            var ggvalue = [];
            for (var i2 = 0; i2 < lv2Arr.length; i2++) {
                var now_gg_value = lv2Arr[i2].value.trim();
                if(now_gg_value == ''){
                    res['status'] = false;
                    res['msg'] = '参数值不能为空！';
                    return res;
                }else{
                    if(ggvalue.indexOf(now_gg_value) == -1){
                        ggvalue.push(now_gg_value);
                    }
                }
                level_2[i2] = {};
                level_2[i2]['attr_id'] = son;
                level_2[i2]['attr_name'] = lv2Arr[i2].value.trim();
                son++;
            }

            level_1[i]['attr_list'] = level_2;

            if (ggstatus == false) {
                res['status'] = false;
                res['msg'] = ggstr;
                return res;
            }
            if (ggvalue.length != lv2Arr.length) {
                res['status'] = false;
                res['msg'] = '请删除值重复的参数项！';
                return res;
            }
            //参数值的判断-end-
        }

        $('#gg_json').val(JSON.stringify( level_1 ))
        var jj = $('#gg_json').val().trim();
        if(jj == ''){
            res['status'] = false;
            res['msg'] = '请完善规格！';
            return res;
        }
//
        if($('.attrinput').length <= 0){
            res['status'] = false;
            res['msg'] = '请填写规格参数！';
            return res;
        }else{
            var attr_last_str = '';
            $('.attrinput').each(function (i,d) {
                if(i % 5 == 0){
                    var attr_s = $(d).attr('data-attrstr')
                    var attr_i = $(d).attr('data-attrid')
                    attr_last_str += attr_s+'___'+attr_i+'___'
                }
                var value = d.value;
                if(i % 5 == 4){
                    attr_last_str += value + '|||';
                }else{
                    attr_last_str += value + '___';
                }
            });
            $('#attr_json').val(attr_last_str)
        }
        var jj2 = $('#attr_json').val().trim();
        if(jj2 == ''){
            res['status'] = false;
            res['msg'] = '请填写规格参数！';
            return res;
        }
        return res;
    }
</script>